#include "core/kernel.h"
#include "core/process.h"

namespace engine {

	namespace core {

		Process::Process()
		:m_IsThread(false) {
			
		}
		
		Process::Process(shared_ptr<Kernel> parent, bool isThread):
		m_Parent(parent),
		m_IsThread(isThread) {

		}

		Process::~Process() {

		}

		///Process any messages in the inbox
		int Process::processInbox() {
			int numMessagesProcessed = 0;

			while (!m_Inbox.empty()) {
				shared_ptr<Message> msg = m_Inbox.front();
				m_Inbox.pop_front();
				
				if (processRecievedMessage(msg)){
					++numMessagesProcessed;
				}
			}

			return numMessagesProcessed;
		}

		///Run the process in a separate thread
		int Process::run() {
			bool done = false;
			while(!done) {
				processInbox();
				prepare(m_Parent->getDT());
				update();
			}
			return 0;
		}

		void Process::setParent(const shared_ptr<Kernel> parent) {
			m_Parent = parent;
		}
		
		const MessageQueue& Process::getOutbox() {
		    return m_Outbox;
		}
		
		void Process::receiveMessage(shared_ptr<Message> msg) {
			m_Inbox.push_back(msg);
		}
		
		void Process::sendMessage(shared_ptr<Message> msg) {
			m_Outbox.push_back(msg);
		}
	}
}
